package com.gxa.learning.pc.service.impl;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.gxa.learning.pc.mapper.MessageMapper;
import com.gxa.learning.pc.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lijianmin
 * @date 2021/12/09  15:59:36
 */
@Service("messageService")
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<Map<String, Object>> selectUserTest(Long id) throws ParseException {
        PageMethod.startPage(1, 1000);
        List<Map<String, Object>> maps = messageMapper.selectUserTest(id);
        for (Map<String, Object> map : maps) {
            Object scoreKey = map.get("scoreKey");
            Object o = redisTemplate.opsForValue().get(TestServiceImpl.TESTKEY + scoreKey);
            if (o != null) {
                Map<String, Object> entries = redisTemplate.opsForHash().entries(scoreKey);
                map.putAll(entries);
            }
            Object endDays = map.get("endDay");
            if (endDays != null) {
                String time = map.get("time").toString();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long endDay = Long.parseLong(endDays.toString());
                Date parse = sdf.parse(time);
                map.put("time", parse);
                long outTime = sdf.parse(time).getTime() + (endDay * 24 * 60 * 60 * 1000);
                long presentTime = System.currentTimeMillis();
                if (presentTime > outTime) {
                    messageMapper.update(Long.parseLong(map.get("scoreId").toString()));
                    map.put("status", 2);
                }
                Date date = new Date(outTime);
                map.put("endDay", sdf.format(date));
            }

        }
        return PageInfo.of(maps);
    }
}
